package com.unism.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class CJson {
	private static final String resultKey = "result";

	// 写出json对象数据
	public static String writeJsonData(JsonResult result, HashMap<String, String> params) {

		JSONObject jobj = new JSONObject();
		// isSucc,获取成功(如果结果为空,说明本来就不存在),返回200
		if (result.isSucc()) {
			if (result.getObject() == null) {
				// 当前无数据
				jobj.put(JsonResult.CODE_KEY, JsonResult.CODE_SUCC_noData);// code.value,
																			// for
																			// example
																			// "300"
				jobj.put(JsonResult.MESSAGE_KEY, result.getMessage()); // code.message,
																		// for
																		// example
																		// "SUCCESS"
				jobj.put(JsonResult.RESULT_KEY, result.getObject()); // result
			} else {
				// 当前有数据
				jobj.put(JsonResult.CODE_KEY, JsonResult.CODE_SUCC);// code.value,
																	// for
																	// example
																	// "200"
				jobj.put(JsonResult.MESSAGE_KEY, ""); // code.message, for
														// example "SUCCESS"
				jobj.put(JsonResult.RESULT_KEY, result.getObject()); // result
			}
		} else {
			jobj.put(JsonResult.CODE_KEY, JsonResult.CODE_FAIL); // code.value,
																	// for
																	// example
																	// "200"
			jobj.put(JsonResult.MESSAGE_KEY, result.getMessage());// code.message,
																	// for
																	// example
																	// "SUCCESS"
		}
		if (params != null) {
			Set<Map.Entry<String, String>> set = params.entrySet();
			Iterator<Map.Entry<String, String>> it = set.iterator();
			Map.Entry<String, String> entry = null;
			while (it.hasNext()) {
				entry = it.next();
				jobj.put(entry.getKey(), entry.getValue());
			}
		}
		return jobj.toString();

	}

	public static String writeJsonObj(Object result) {

		JSONObject jsonObject = JSONObject.fromObject(result);
		return jsonObject.toString();
	}

	public static String writeJsonArray(Object result) {

		JSONArray jsonObject = JSONArray.fromObject(result);

		return jsonObject.toString();
	}

	public static String writeJsonMap(Object result, HashMap<String, String> params) {

		JSONObject jobj = new JSONObject();
		if (result != null) {
			jobj.put(resultKey, result);
		}

		if (params != null) {
			Set<Map.Entry<String, String>> set = params.entrySet();
			Iterator<Map.Entry<String, String>> it = set.iterator();
			Map.Entry<String, String> entry = null;
			while (it.hasNext()) {
				entry = it.next();
				jobj.put(entry.getKey(), entry.getValue());
			}
		}

		return jobj.toString();
	}

}
